package com.megalith.controller;

import com.megalith.domain.Student;
import com.megalith.service.StudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelToHtmlUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Description TODO
 * @Author lfp
 * @Date 2021/4/22 21:41
 * @Version 1.0
 */
@Controller
@Api(value = "AutoPoi测试")
@RequestMapping("excel")
public class AutoPoiController {

    @Autowired
    private StudentService studentService;

    @ApiOperation(value = "测试导出")
    @GetMapping("export")
    public void exportExcel(HttpServletResponse response) throws IOException {
        List<Student> mockData = studentService.getMockData();

        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("学生表","学生"),
                Student.class, mockData);

        ServletOutputStream outputStream = response.getOutputStream();
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/force-download");
        response.setHeader("Content-Disposition","attachment;filename=student.xlsx");
        //response.setContentType("application/octet-stream;charset=UTF-8");

        workbook.write(outputStream);
        workbook.close();
    }

    @ApiOperation(value = "预览",notes = "直接用浏览器访问地址")
    @GetMapping("review")
    public void reviewExcel(HttpServletResponse response) throws IOException {
        List<Student> mockData = studentService.getMockData();

        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("学生表","学生"),
                Student.class, mockData);

        response.getOutputStream().write(ExcelToHtmlUtil.toAllHtml(workbook).getBytes());

    }
}